package com.gyt.manager.conf.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author v_yantgao
 */
@Configuration
@MapperScan(basePackages = {"com.gyt.manager.dao.risk"}, sqlSessionTemplateRef = "riskSqlSessionTemplate")
public class RiskDataSourceConfig {

    private static Logger logger = LoggerFactory.getLogger(RiskDataSourceConfig.class);


    /**
     * 主数据源
     * @return
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.risk")
    public DataSource riskDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 然后创建 SqlSessionFactory
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean
    @Primary
    public SqlSessionFactory riskSqlSessionFactory(@Qualifier("riskDataSource") DataSource dataSource){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        try {
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:config/mapper/risk/*.xml"));
            return bean.getObject();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 创建事务管理器
     * @param dataSource
     * @return
     */
    @Bean
    @Primary
    public DataSourceTransactionManager riskTransactionManager(@Qualifier("riskDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    /**
     * 包装到 SqlSessionTemplate 中
     * @param sqlSessionFactory
     * @return
     * @throws Exception
     */
    @Bean
    @Primary
    public SqlSessionTemplate riskSqlSessionTemplate(@Qualifier("riskSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * 初始化对应的spring jdbc对象
     * @param dataSource
     * @return
     */
    @Bean
    public JdbcTemplate riskJdbcTemplate(@Qualifier("riskDataSource") DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

}
